package com.ai.bitcoin.controller;

import com.ai.bitcoin.jpa.entity.BccBasicInfo;
import com.ai.bitcoin.jpa.entity.BccUserBonusConfig;
import com.ai.bitcoin.jpa.service.BccBasicInfoService;
import com.ai.bitcoin.jpa.service.UserBonusService;
import com.ai.bitcoin.utils.EmojiFilterUtils;
import com.ai.bitcoin.utils.HttpClientUtils;
import com.ai.bitcoin.vo.UserEncourageReq;
import com.ai.bitcoin.vo.UserEncourageResponse;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("wechatGroup")
@Slf4j
public class WechatGroupController {

    @Value("${asyncTimeout}")
    long asyncTimeout;

    @Autowired
    private UserBonusService userBonusService;
    @Autowired
    BccBasicInfoService bccBasicInfoService;

    //用户剩余plc激励 微信群
    @RequestMapping(value = "/message", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public DeferredResult<ResponseEntity<UserEncourageResponse>> plcLeftEncourage(@RequestBody Map messageInfo) {

        String messageContent = MapUtils.getString(messageInfo, "messageContent");
        messageContent = StringUtils.replace(messageContent, " ", "");
        messageContent = StringUtils.replace(messageContent, "\n", "");
        messageContent = StringUtils.replace(messageContent, "\t", "");
        messageContent = StringUtils.replace(messageContent, "\r", "");
        messageContent = EmojiFilterUtils.filterEmoji(messageContent);
        String message = messageContent;

        String messageType = MapUtils.getString(messageInfo, "messageType");

        DeferredResult<ResponseEntity<UserEncourageResponse>> deferredResult = new DeferredResult<>(10000000L);
        UserEncourageReq request = new UserEncourageReq();
        request.setGroupName(MapUtils.getString(messageInfo, "groupName"));
        request.setGroupOwnerName(MapUtils.getString(messageInfo, "groupOwnerName"));
        if (StringUtils.equals(messageType, "01")) {
            request.setParentNickname(MapUtils.getString(messageInfo, "senderName"));
            request.setNickname(MapUtils.getString(messageInfo, "beInvitedName"));
        }
        else if (StringUtils.equals(messageType, "02")) {
            request.setNickname(MapUtils.getString(messageInfo, "senderName"));
        }

        //机器人自主操作过滤
        if (StringUtils.equals(MapUtils.getString(messageInfo, "senderName"), "你")) {
            deferredResult.setResult(null);
            return deferredResult;
        }

        CompletableFuture.supplyAsync(() -> {
                    String eventTypeCd = null;
                    //系统消息
                    if (StringUtils.equals(messageType, "01")) {
                        if (StringUtils.isNotEmpty(MapUtils.getString(messageInfo, "beInvitedName"))) {
                            //邀请入群
                            eventTypeCd = "0203";
                        }
                        else {
                            eventTypeCd = "0204";
                        }

                    }
                    else if (StringUtils.equalsAny(StringUtils.lowerCase(message), "查看挖矿机制", "我的plc")) {
                        //可挖PLC信息
                        eventTypeCd = "0206";
                    }
                    else if (StringUtils.equals(message, "我的邀请海报")) {
                        eventTypeCd = "0311";
                    }
                    else if (StringUtils.equals(message, "签到")) {
                        eventTypeCd = "0201";
                    }
                    else if (StringUtils.equalsAny(StringUtils.lowerCase(message), "plc", "评链网")) {
                        eventTypeCd = "0310";
                    }
                    else {
                        BccBasicInfo bccBasicInfo = bccBasicInfoService.getByKeyword(StringUtils.lowerCase(message));
                        if (bccBasicInfo != null) {
                            eventTypeCd = "0202";
                            request.setBccBasicInfo(bccBasicInfo);
                        }
                        else {
                            bccBasicInfo = bccBasicInfoService.subscribeKeywords(message);
                            if (bccBasicInfo != null) {
                                //订阅关键字
                                eventTypeCd = "0306";
                                request.setBccBasicInfo(bccBasicInfo);
                            }
                        }
                    }

                    if (eventTypeCd == null) {
                        UserEncourageResponse response = new UserEncourageResponse();

                        //使用青云客回复
                        if (StringUtils.equals(messageType, "02") && StringUtils.startsWith(message, "@小评@评链网")) {
                            try {

                                String sendMessage = StringUtils.replace(message, "@小评@评链网", "");
                                sendMessage = URLEncoder.encode(StringUtils.trim(sendMessage));
                                String qingyunResult = HttpClientUtils.doGet("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + sendMessage, 60000);
                                Map result = JSON.parseObject(qingyunResult, Map.class);
                                if (MapUtils.getInteger(result, "result") == 0) {
                                    response.getMessageList().add(
                                            "@" + MapUtils.getString(messageInfo, "senderName") + " " + MapUtils.getString(result, "content")
                                    );
                                }
                            } catch (Exception ignored) {
                            }
                        }


                        return new ResponseEntity(response, null, HttpStatus.OK);
                    }
                    else {
                        UserEncourageResponse response = userBonusService.sendBonus(BccUserBonusConfig.EVENT_SOURCE_GROUP, eventTypeCd, request);
                        return new ResponseEntity(response, HttpStatus.OK);

                    }

                }
        ).whenCompleteAsync((result, throwable) ->
                {
                    deferredResult.setResult(result);
                    if (throwable != null) {
                        throwable.printStackTrace();
                    }
                }

        );
        return deferredResult;
    }

}
